-module(company).
-compile(export_all).

-include_lib("stdlib/include/qlc.hrl").
-include("company.hrl").

init() ->
    mnesia:create_schema(nodes()),
    mnesia:start(),
    mnesia:create_table(employee,
        [{attributes,record_info(fields,employee)}]),
    mnesia:create_table(dept,[{attributes,record_info(fields,dept)}]),
    mnesia:create_table(project,[{attributes,record_info(fields,project)}]),
    mnesia:create_table(manager,[{type, bag},
        {attributes,record_info(fields,manager)}]),
    mnesia:create_table(at_dep,[{type, set},
               {attributes,record_info(fields,at_dep)}]),
    mnesia:create_table(in_proj,[{type, bag}, 
               {attributes,record_info(fields,in_proj)}]).

insert_emp(Emp, DeptId, ProjNames) ->
    Eno = Emp#employee.emp_no,
    Fun = fun() ->
                mnesia:write(Emp),
                Manager = #manager{dept_id=DeptId, emp_no=Eno},
                mnesia:write(Manager),
                AtDep = #at_dep{emp_no=Eno, dept_id=DeptId},
                mnesia:write(AtDep),
                mk_projs(Eno, ProjNames)
          end,
    mnesia:transaction(Fun).

mk_projs(Eno, [ProjName|T]) ->
    mnesia:write(#in_proj{emp_no=Eno, proj_name=ProjName}),
    mk_projs(Eno, T);
mk_projs(_Eno, []) -> ok.

raise(Eno, Raise) ->
    F = fun() ->
            [E] = mnesia:read(employee, Eno, write),
            Salary = E#employee.salary + Raise,
            New = E#employee{salary=Salary},
            mnesia:write(New)
        end,
    mnesia:transaction(F).

all_females() ->
    F = fun() ->
            Female = #employee{sex=female, name='$1', _='_'},
            mnesia:select(employee, [{Female, [], ['$1']}])
        end,
    mnesia:transaction(F).

demo(all_females) ->
    do(qlc:q([E#employee.name || E <- mnesia:table(employee), 
                                 E#employee.sex == female])).

do(Q) ->
    F = fun() ->
            qlc:e(Q)
        end,
    mnesia:transaction(F).

